import type { LngLat } from 'mapbox-gl';

export class PositionMarker {
  map: mapboxgl.Map | null = null;

  constructor(map: mapboxgl.Map) {
    this.map = map;
  }

  private resolve: (value: [LngLat?, Error?]) => void = () => {};
  private reject: (reason?: string) => void = () => {};

  private mapClickHandler = (e: mapboxgl.MapMouseEvent) => {
    if (!this?.map) return this.reject('map is not ready');
    this.map.getCanvas().style.cursor = '';
    // 获取坐标并格式化
    const coords = e.lngLat;

    this.resolve([coords, undefined]);
  };

  async startPointPickingAsync(): Promise<[LngLat?, Error?]> {
    if (!this?.map) return [undefined, new Error('Map not initialized')];
    // 设置地图光标样式
    this.map.getCanvas().style.cursor = 'crosshair';

    // 创建一个Promise，用于异步获取坐标
    return new Promise<[LngLat?, Error?]>((resolve, reject) => {
      if (!this?.map) return reject('map is not ready');
      this.resolve = resolve;
      this.reject = reject;
      // 添加临时点击事件
      this?.map?.once('click', this.mapClickHandler);

      const escHandler = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
          this.stop();
          if (!this?.map) return this.reject('map is not ready');
          this.resolve([undefined, new Error('picking canceled')]);
          window.removeEventListener('keydown', escHandler);
        }
      };
      window.addEventListener('keydown', escHandler);
    });
  }

  stop() {
    if (this.map) {
      this.map.getCanvas().style.cursor = '';
      this.map.off('click', this.mapClickHandler);
    }
  }
}
